package com.price.compare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.price.compare.common.*;
import com.price.compare.entity.Material;
import com.price.compare.mapper.MaterialMapper;
import com.price.compare.qo.MaterialQO;
import com.price.compare.service.MaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * ç‰©æ–™è¡¨ 服务实现类
 * </p>
 *
 * @author ccp
 * @since 2024-11-06
 */
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements MaterialService {

    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired
    private MaterialMapper materialMapper;

    @Override
    public JsonResult queryPageList(MaterialQO materialQO) {
        if (null == materialQO.getPageNum() || null == materialQO.getPageSize()) {
            return JsonResult.error("页码和页大小不能为空");
        }
        IPage<Material> page = new Page<>(materialQO.getPageNum(), materialQO.getPageSize());
        IPage<Material> iPage = materialMapper.selectPage(page, getQueryParam(materialQO));
        return JsonResult.ok(iPage);
    }

    /**
     * 必填项校验
     *
     * @param obj
     * @return
     */
    private String validRequire(Material obj) {
        StringBuilder sb = new StringBuilder("");
        if (StringUtils.isEmpty(obj.getMaterialCode())) {
            if (StringUtils.isEmpty(sb.toString())) {
                sb.append(MaterialColEnum.MATERIAL_MATERIALCODE.getTitle());
            } else {
                sb.append("、").append(MaterialColEnum.MATERIAL_MATERIALCODE.getTitle());
            }
        }
        if (StringUtils.isEmpty(obj.getMaterialShortText())) {
            if (StringUtils.isEmpty(sb.toString())) {
                sb.append(MaterialColEnum.MATERIAL_MATERIALSHORTTEXT.getTitle());
            } else {
                sb.append("、").append(MaterialColEnum.MATERIAL_MATERIALSHORTTEXT.getTitle());
            }
        }
        if (StringUtils.isEmpty(obj.getMaterialLongText())) {
            if (StringUtils.isEmpty(sb.toString())) {
                sb.append(MaterialColEnum.MATERIAL_MATERIALLONGTEXT.getTitle());
            } else {
                sb.append("、").append(MaterialColEnum.MATERIAL_MATERIALLONGTEXT.getTitle());
            }
        }
        if (null == obj.getMoney()) {
            if (StringUtils.isEmpty(sb.toString())) {
                sb.append(MaterialColEnum.MATERIAL_MONEY.getTitle());
            } else {
                sb.append("、").append(MaterialColEnum.MATERIAL_MONEY.getTitle());
            }
        }
        return sb.toString();
    }

    /**
     * Material导入属性对应map
     *
     * @return
     */
    private Map<String, String> getTitleMap() {
        Map<String, String> map = new HashMap<>();
        map.put("物料号", "material_code");
        map.put("物料短描述", "material_short_text");
        map.put("物料长描述", "or_tmaterial_long_textext");
        map.put("未税报价", "money");
        return map;
    }

    /**
     * 查询 Material表 所有数据
     */
    @Override
    public List<Material> queryList() {
        QueryWrapper<Material> queryWrapper = new QueryWrapper<>();
        return materialMapper.selectList(queryWrapper);
    }

    @Override
    public JsonResult batchAdd(List<Material> list) {
        return JsonResult.ok();
    }

    @Override
    public JsonResult batchUpdate(List<Material> list) {
        return JsonResult.ok();
    }

    @Override
    @Transactional
    public JsonResult batchDelete(List<Long> ids) {
        if (null == ids || 0 == ids.size()) {
            return JsonResult.error("ids为空，请至少选择一条数据！");
        }

        materialMapper.deleteBatchIds(ids);
        return JsonResult.ok("删除成功");
    }

    /**
     * 设置查询参数
     *
     * @param materialQO
     * @return
     */
    private QueryWrapper<Material> getQueryParam(MaterialQO materialQO) {
        if (null == materialQO) {
            return null;
        }
        QueryWrapper<Material> queryWrapper = new QueryWrapper<>();
        // 所有待查询的条件
        if (null != materialQO.getId()) {
            queryWrapper.lambda().eq(Material::getId, materialQO.getId());
        }
        if (StringUtils.isNotEmpty(materialQO.getMaterialCode())) {
            queryWrapper.lambda().like(Material::getMaterialCode, materialQO.getMaterialCode());
        }
        if (StringUtils.isNotEmpty(materialQO.getMaterialShortText())) {
            queryWrapper.lambda().like(Material::getMaterialShortText, materialQO.getMaterialShortText());
        }
        if (StringUtils.isNotEmpty(materialQO.getMaterialLongText())) {
            queryWrapper.lambda().like(Material::getMaterialLongText, materialQO.getMaterialLongText());
        }
        if (materialQO.getMoney() != null) {
            queryWrapper.lambda().eq(Material::getMoney, materialQO.getMoney());
        }
        // 批量查询
//        if (null != materialQO.getIdList() && 0 != materialQO.getIdList().size()) {
//            queryWrapper.lambda().in(Material::getId, materialQO.getIdList());
//        }
//        if (null != materialQO.getOrTextList() && 0 != materialQO.getOrTextList().size()) {
//            queryWrapper.lambda().in(Material::getOrText, materialQO.getOrTextList());
//        }

        return queryWrapper;
    }

    @Override
    public void downloadData(MaterialQO materialQO, HttpServletResponse response) {
        List<Material> dataList = materialMapper.selectList(getQueryParam(materialQO));
        String fileName = "Material数据信息";
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        String[] headers = MaterialColEnum.getHeadersNoSettlement();
        String[] keys = MaterialColEnum.getProsNoSettlement();
        //  ExcelUtil2.exportExcel(fileName, dataList, headers, keys, response);
        LargeExcelExportUtil.exportExcel(fileName, dataList, headers, keys, response);
    }

    @Override
    public JsonResult getList(MaterialQO materialQO) {
        QueryWrapper<Material> qw = getQueryParam(materialQO);
        return JsonResult.ok(materialMapper.selectList(qw));
    }

    @Override
    public JsonResult add(Material obj) {
        String email = "";
        if (StringUtils.isEmpty(email)) {
            return JsonResult.error("未找到用户邮箱信息，请先登录");
        }

        String userName = "";
        return materialMapper.insert(obj) > 0 ? JsonResult.ok("操作成功！") : JsonResult.error("操作失败");
    }

    @Override
    public JsonResult update(Material material) {
//        String email = UserUtil.getUserEmail();
//        if (StringUtils.isEmpty(email)) {
//              return JsonResult.error("未找到用户邮箱信息，请先登录");
//        }
        if (null == material.getId()) {
            return JsonResult.error("id不能为空");
        }

        int flag = materialMapper.updateById(material);
        return flag > 0 ? JsonResult.ok("操作成功！") : JsonResult.error("操作失败");
    }

    @Override
    @Transactional
    public JsonResult delete(Long id) {
        if (null == id) {
            return JsonResult.error("id不能为空");
        }
        return materialMapper.deleteById(id) > 0 ? JsonResult.ok("操作成功！") : JsonResult.error("操作失败");
    }

    /**
     * 校验数据，上传Excel的数据
     *
     * @param jsonObjectList
     * @return
     */
    private String importExcelDataToDb(JSONArray jsonObjectList) {
        int size = jsonObjectList.size();
        StringBuilder errorMsg = new StringBuilder("");
        List<Material> excelList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            JSONObject jo = null;
            try {
                jo = jsonObjectList.getJSONObject(i);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //导入字段调整多一份数据库字段
            Material obj = JSONUtil.toBean(jo.toString(), Material.class);
            //验证是否有为空
            String msg = validRequire(obj);
            if (StringUtils.isNotEmpty(msg)) {
                errorMsg.append("第").append(i + 2).append("行: ").append(msg).append("为空").append(";").append("<br />");
                continue;
            }
            excelList.add(obj);
        }
        if (StringUtils.isNotEmpty(errorMsg.toString())) {
            log.error("Material上传失败:" + errorMsg);
            return errorMsg.toString();
        } else {
            saveBatch(excelList);
            return "";
        }
    }

    /**
     * 上传文件并校验
     * <p>
     * 数据校验
     * 字段计算/匹配
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public JsonResult uploadExcel(MultipartFile file) {
        if (null == file) {
            return JsonResult.error("文件不能为空");
        }
        try {
            //错误信息
            StringBuilder errorMsg = new StringBuilder("");
            //获取当前用户的邮箱地址
            String email = "";
            Map<String, String> titleMap = getTitleMap();
            Map<String, Object> map = ExcelImportUtil.readExcel(file, 1, titleMap);    // 修改
            JSONArray jsonObjectList = (JSONArray) map.get("data");

            //判断表格数据为空
            if (null == jsonObjectList || 0 == jsonObjectList.size()) {
                return JsonResult.ok(BaseDataConstant.EXCEL_NO_DATA);
            }
            //数据校验
            //字段计算/匹配
            String flagStr = importExcelDataToDb(jsonObjectList);
            if (StringUtils.isNotEmpty(flagStr)) {
                log.error("Material上传失败:" + flagStr);
                return JsonResult.error(flagStr);
            } else {
                return JsonResult.ok(BaseDataConstant.EXCEL_UPLOAD_SUCCESS);
            }

        } catch (Exception e) {
            log.error("[Material]上传错误：", e);
            return JsonResult.error("上传错误");
        }
    }

    /**
     * 根据id查询Material信息
     *
     * @param id
     * @return
     */
    @Override
    public Material getOrById(Long id) {
        QueryWrapper<Material> q = new QueryWrapper<>();
        q.lambda().eq(Material::getId, id);
        q.last(" limit 1");
        return materialMapper.selectOne(q);
    }
}
